package com.testitems.config.security;

import com.testitems.enums.RoleEnum;
import com.testitems.repo.entity.User;
import com.testitems.service.user.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUserNameFromCache(username);
        if (user == null) {
            throw new UsernameNotFoundException("当前用户不存在");
        }
        RoleEnum roleEnum = RoleEnum.valueOf(user.getRoleLevel());
        return new UserInfo(username,
                user.getPassword(),
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList(roleEnum.name()),
                user.getId(),
                user.getName());
    }
}
